﻿using System;
using System.IO;
using System.Reflection;

using Styx.Common;
using Styx.Plugins;

namespace AnimusLoader
{
    public class AnimusLoader : HBPlugin
    {
        private static bool _initialized;
        private readonly static string _dllmain = (Utilities.AssemblyDirectory + @"\Plugins" + @"\Animus" + @"\Animus.dll");
        private Assembly _AnimusPluginAssembly;
        private HBPlugin _AnimusPluginInstance;

        public override string Name
        {
            get
            {
                if (!_initialized)
                {
                    _AnimusPluginAssembly = Assembly.Load(File.ReadAllBytes(_dllmain));
                    _AnimusPluginInstance = (HBPlugin)_AnimusPluginAssembly.CreateInstance("SiN.Animus");
                    _initialized = true;
                }
                return _AnimusPluginInstance != null ? _AnimusPluginInstance.Name : "";
            }
        }

        public override Version Version { get { return _AnimusPluginInstance != null ? _AnimusPluginInstance.Version : new Version(0, 0, 0); } }
        public override string Author { get { return _AnimusPluginInstance != null ? _AnimusPluginInstance.Author : ""; } }

        public override string ButtonText { get { return _AnimusPluginInstance != null ? _AnimusPluginInstance.ButtonText : ""; } }
        public override bool WantButton { get { return _AnimusPluginInstance != null && _AnimusPluginInstance.WantButton; } }
        public override void OnButtonPress() { if (_AnimusPluginInstance != null) _AnimusPluginInstance.OnButtonPress(); }

        public override void OnEnable() { if (_AnimusPluginInstance != null) _AnimusPluginInstance.OnEnable(); }
        public override void OnDisable() { if (_AnimusPluginInstance != null) _AnimusPluginInstance.OnDisable(); }
        public override void Pulse() { if (_AnimusPluginInstance != null) _AnimusPluginInstance.Pulse(); }

        protected virtual bool IsFileLocked(FileInfo file)
        {
            FileStream stream = null;
            try { stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None); }
            catch (IOException) { return true; }
            finally { if (stream != null) { stream.Close(); } }
            return false;
        }
    }
}